<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-31 16:44:32
 * @Last Modified time: 2023-02-13 16:47:43
 */
namespace app\api\controller\store;	
use think\facade\App;
use app\common\services\store\CartService;
use app\common\services\store\order\CheckoutService;

/**
 * 购物车
 * Class Cart
 */
class Cart extends \app\api\controller\Base
{ 	
    /**
     * CartService constructor.
     * @param App $app
     */
    public function __construct(App $app,CartService $service)
    {
        parent::__construct($app);
        $this->service = $service->init($this->user);
    }

    /**
     * 获取购物车列表
     * @force(false)
     * @method(GET)
     */
    public function list()
    {
        // 请求参数
        $param = $this->request->param();
        $cartIds = isset($param['cart_ids']) ? $param['cart_ids'] : '';
        // 购物车商品列表
        $goodsList = $this->service->getList($cartIds);
        if(empty($goodsList)) $this->success([]);
        // 获取订单结算信息
        $orderInfo = CheckoutService::instance()->onCheckout($this->user, $goodsList);
        $this->success('获取成功',$orderInfo);
    }

    /**
     * 加入购物车
     * @method(POST)
     */
    public function create()
    {
        $goodsId = $this->request->param('goods_id');
        $goodsNum = $this->request->param('goods_num');
        $goodsSkuId = $this->request->param('goods_sku_id');
        if (!$this->service->create($goodsId, $goodsNum, $goodsSkuId)) {
            $this->error($this->service->getError() ?:'加入购物车失败');
        }
        // 购物车商品总数量
        $totalNum = $this->service->getGoodsNums();
        $this->success('加入购物车成功', ['cart_total_num' => $totalNum]);
    }

    /**
     * 修改购物车商品数量
     * @method(PUT)
     */
    public function update()
    {
        $goodsId = $this->request->param('goods_id');
        $goodsNum = $this->request->param('goods_num');
        $goodsSkuId = $this->request->param('goods_sku_id');
        $this->service->update($goodsId, $goodsNum, $goodsSkuId);
        $this->success('修改成功');
    }

    /**
     * 删除购物车中指定商品
     * @method(DELETE)
     */
    public function delete()
    {
        $cartId = $this->request->param('cart_id');
        $this->service->delete($cartId);
        $this->success('删除成功');
    }

    /**
     * 清空购车
     * @method(DELETE)
     */
    public function clearAll(){
        $this->service->clearAll();
        $this->success('删除成功');
    }
}